package com.chen.base.module.mybatis.methods;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.chen.base.utils.basic.StringUtil;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;


/**
 * @author ChenJinLong
 */
public class InsertAllOracle extends AbstractMethod {

    public InsertAllOracle() {
        this(StringUtil.initialToLowerCase(InsertAllOracle.class.getSimpleName()));
    }

    /**
     * @param name 方法名
     * @since 3.5.0
     */
    public InsertAllOracle(String name) {
        super(name);
    }

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = "<script>INSERT ALL  %s  SELECT 1 FROM DUAL</script>";
        String insertSql = prepareValuesSqlForOracleBatchInsertAll(tableInfo);
        String sqlResult = String.format(sql, insertSql);

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
        return this.addInsertMappedStatement(mapperClass, modelClass, "insertAll",
                sqlSource, new NoKeyGenerator(), null, null);
    }

    private String prepareFieldSql(TableInfo tableInfo) {
        StringBuilder fieldSql = new StringBuilder();
        fieldSql.append(tableInfo.getKeyColumn()).append(",");
        tableInfo.getFieldList().forEach(x -> fieldSql.append(x.getColumn()).append(","));
        fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
        fieldSql.insert(0, "(");
        fieldSql.append(")");
        return fieldSql.toString();
    }

    private String prepareValuesSqlForOracleBatchInsertAll(TableInfo tableInfo) {
        StringBuilder valueSql = new StringBuilder();
        String fieldSql = prepareFieldSql(tableInfo);
        valueSql.append("<foreach collection=\"list\" item=\"item\" index=\"index\" >");
        valueSql.append("\r\n INTO ");
        valueSql.append(tableInfo.getTableName());
        valueSql.append(fieldSql);
        valueSql.append(" values (");
        valueSql.append("#{item.").append(tableInfo.getKeyProperty()).append("},");
        for (TableFieldInfo tableFieldInfo : tableInfo.getFieldList()) {
            if (tableFieldInfo.getPropertyType().getSimpleName().equalsIgnoreCase("DOUBLE")) {
                valueSql.append("#{item.").append(tableFieldInfo.getProperty()).append(",jdbcType=DOUBLE},");
            }else {
                valueSql.append("#{item.").append(tableFieldInfo.getProperty()).append(",jdbcType=VARCHAR},");
            }
        }
        //去掉最后一个逗号
        valueSql.delete(valueSql.length() - 1, valueSql.length());
        valueSql.append(")\r\n");
        valueSql.append("</foreach>");
        return valueSql.toString();
    }
}
